package com.coc.core.utils;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.coc.entity.system.SysUser;
import java.lang.reflect.Field;

/**
 *获取对象非空属性工具类
 * @param <T>
 */
public class CheckObjField<T> {
    private final static String UNDERLINE = "_";

    /**
     *注意!!!,不要将在数据库里没有的例赋着值传来解析,否则会报错Unknown column
     * @param obj 传入的对象
     * @return 返回mybatis-plus的查询条件
     * @throws Exception
     */
    public  QueryWrapper<T> getFields(T obj){
        QueryWrapper<T> qw = new QueryWrapper<>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for (Field f:fields){
            f.setAccessible(true);
            try {
                if (f.get(obj) != null && StrUtil.isNotBlank(f.get(obj).toString())) {
                    String fn= f.getName();
                    String s = humpToUnderline(fn);
                    System.out.printf(s);
                    qw.eq(s,f.get(obj));
                }
            }catch (Exception e){
                e.printStackTrace();
                return qw;
            }

        }
        return qw;
    }
    /***
     * 驼峰命名转为下划线命名
     *
     * @param para
     *        驼峰命名的字符串
     */

    public  String humpToUnderline(String para) {
        StringBuilder sb = new StringBuilder(para);
        int temp = 0;//定位
        if (!para.contains(UNDERLINE)) {
            for (int i = 0; i < para.length(); i++) {
                if (Character.isUpperCase(para.charAt(i))) {
                    sb.insert(i + temp, UNDERLINE);
                    temp += 1;
                }
            }
        }
        return sb.toString().toLowerCase();
    }

    public static void main(String[] args) throws Exception{
        SysUser sysUser = new SysUser();
        sysUser.setInsertUid(38);
        sysUser.setId(23);
        sysUser.setToken("hello");
        QueryWrapper<SysUser> fields = new CheckObjField<SysUser>().getFields(sysUser);
    }
}
